<template>
  <Dialog
    :visible="exportAllDialogVisible"
    @close="handleExportAllDialogVisible"
    width="80%"
    center
  >
    <ExportTable
      :heads="UserCommonHeads"
      :headMap="userCommonMap"
      :tableData="tableData"
      @moveUp="handleMoveUp"
      @moveDown="handleMoveDown"
    >
    </ExportTable>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleExportAllDialogVisible">取消</el-button>
        <el-button type="primary" @click="handleExportAll">确认导出</el-button>
      </span>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { reactive } from "vue";
import { utils, writeFile } from "xlsx";
import { useStore } from "vuex";

import ExportTable from "@/components/ExportTable.vue";
import Dialog from '@/components/common/Dialog.vue';

import { UserCommonHeads } from "@/data/tableConfig.ts";
import { userCommonMap } from "@/data/tableMap.ts";

const props = defineProps(["exportAllDialogVisible", "tableData"]);
const emits = defineEmits(["closeExportAllDialog"]);

const handleMoveUp = (index: number) => {
  [props.tableData[index], props.tableData[index - 1]] = [
    props.tableData[index - 1],
    props.tableData[index],
  ];
};

const handleMoveDown = (index: number) => {
  [props.tableData[index], props.tableData[index + 1]] = [
    props.tableData[index + 1],
    props.tableData[index],
  ];
};

const handleExportAllDialogVisible = () => {
  emits("closeExportAllDialog");
};

const store = useStore();

const handleExportAll = () => {
  const exportHeads = UserCommonHeads.map((head: IObj) => head.value);

  const exportData = [exportHeads];

  for (const item of props.tableData) {
    const rowData: IObj[] = [];

    for (const exportHead of exportHeads) {
      if (exportHead === "所在社团") {
        const key = item[userCommonMap[exportHead]];
        rowData.push(store.getters.organizationMap[key]);
      } else {
        rowData.push(item[userCommonMap[exportHead]]);
      }
    }

    exportData.push(rowData);
  }

  let ws = utils.aoa_to_sheet(exportData);
  let wb = utils.book_new();
  utils.book_append_sheet(wb, ws, "用户列表"); // 工作簿名称
  writeFile(wb, "用户列表.xlsx"); // 保存的文件名

  handleExportAllDialogVisible();
};
</script>

<style lang="less" scoped>
.myform {
  .top {
    width: 100%;
    display: flex;
    justify-content: space-between;

    :deep(.el-form-item) {
      width: 48%;
    }
  }

  :deep(.el-textarea__inner) {
    height: 100px;
    resize: none;
  }
}
</style>
